/*
 * Bind our project plan tool to work with Google Cal API
 * Ido Green 
 * Created on February 15, 2008, 3:43 PM
 * 
 * http://idojava.blogspot.com/
 */
package ido.com.ui;

import ido.com.util.FileUtil;
import ido.com.util.GCal;
import ido.com.util.GCalEvent;
import ido.com.util.ParsePlan;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JLabel;
import javax.swing.JOptionPane;

/**
 *
 * @author  greenido
 */
public class MainFrame extends javax.swing.JFrame {

    private GCal gcal;
    private ParsePlan parser;
    private ArrayList<String> projectsUrls = new ArrayList<String>();

    /** Creates new form MainFrame */
    public MainFrame() throws Exception {
        initComponents();
        gcal = new GCal();
        gcal.setFeed();
        parser = new ParsePlan();
        initUrls();
    }

    private void initUrls() {
        projectsUrlsArea.setText("");
        String tmpUrl = " ";
        int i = 1;
        while (tmpUrl != null) {
            projectsUrlsArea.setText(projectsUrlsArea.getText() + "\n" + tmpUrl);
            tmpUrl = FileUtil.sharedInstance.getProperty("pro" + i);
            i++;
        }


    }

    private void setUrlsFromArea() {
        StringTokenizer st = new StringTokenizer(projectsUrlsArea.getText(), "\n");
        while (st.hasMoreTokens()) {
            String tmp = st.nextToken();
            if (tmp.contains("http://")) {
                projectsUrls.add(tmp.trim());
            }
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        cleanCalButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        cleanStatusArea = new javax.swing.JTextArea();
        updateCalButton = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        updateStatusArea = new javax.swing.JTextArea();
        exitButton = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jScrollPane3 = new javax.swing.JScrollPane();
        projectsUrlsArea = new javax.swing.JTextArea();
        jLabel4 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Google Calendar + iTeamWork Utility");
        setBackground(new java.awt.Color(51, 153, 255));

        cleanCalButton.setText("Clean");
        cleanCalButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cleanCalButtonActionPerformed(evt);
            }
        });

        cleanStatusArea.setColumns(20);
        cleanStatusArea.setLineWrap(true);
        cleanStatusArea.setRows(5);
        cleanStatusArea.setToolTipText("raw msg. so you'll know what is going on");
        jScrollPane1.setViewportView(cleanStatusArea);

        updateCalButton.setText("Update");
        updateCalButton.setToolTipText("Yo - please check that the calendar is clean!");
        updateCalButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                updateCalButtonActionPerformed(evt);
            }
        });

        updateStatusArea.setColumns(20);
        updateStatusArea.setLineWrap(true);
        updateStatusArea.setRows(5);
        updateStatusArea.setToolTipText("The events that are commited to Google Calendar");
        jScrollPane2.setViewportView(updateStatusArea);

        exitButton.setText("Exit");
        exitButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitButtonActionPerformed(evt);
            }
        });

        jLabel2.setText("Projects");

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/etc/3_32.png"))); // NOI18N

        jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/etc/4_32.png"))); // NOI18N

        projectsUrlsArea.setColumns(20);
        projectsUrlsArea.setRows(5);
        jScrollPane3.setViewportView(projectsUrlsArea);

        jLabel4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/etc/3_32.png"))); // NOI18N

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, jScrollPane3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 514, Short.MAX_VALUE)
                    .add(layout.createSequentialGroup()
                        .add(jLabel4)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jLabel2))
                    .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 514, Short.MAX_VALUE)
                    .add(layout.createSequentialGroup()
                        .add(jLabel3)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(cleanCalButton))
                    .add(layout.createSequentialGroup()
                        .add(jLabel1)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(updateCalButton))
                    .add(jScrollPane2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 514, Short.MAX_VALUE)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, exitButton))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(jLabel2)
                    .add(jLabel4))
                .add(4, 4, 4)
                .add(jScrollPane3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel3)
                    .add(cleanCalButton))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(jLabel1)
                    .add(updateCalButton))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jScrollPane2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(18, 18, 18)
                .add(exitButton)
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    private void cleanCalButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cleanCalButtonActionPerformed
        try {
            setUrlsFromArea();
            for (String curUrl : projectsUrls) {
                System.out.println("Working on: " + curUrl);
                parser.parsePage(curUrl);
                int j = 0;
                int i = gcal.queryCal(parser.getProjectName(), cleanStatusArea);
                // because it take more the one time to remove all the events...
                while (j < 4 && i > 0) {
                    i = gcal.queryCal(parser.getProjectName(), cleanStatusArea);
                    j++;
                }
            }
            JOptionPane.showMessageDialog(this, new JLabel("OK - Done with cleaning"));
        } catch (Exception ex) {
            Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, "Could not clean the GCAL from old events!", ex);
            JOptionPane.showMessageDialog(this, new JLabel("Could not clean the GCal!"));
        }
        

}//GEN-LAST:event_cleanCalButtonActionPerformed

    private void exitButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitButtonActionPerformed
        System.exit(0);
    }//GEN-LAST:event_exitButtonActionPerformed

    private void updateCalButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_updateCalButtonActionPerformed

        try {
            int i = 0;
            FileUtil.sharedInstance.writeToFile(GCal.GANNT_FILE, "<data>");
            ArrayList<GCalEvent> events = parser.getEvents();
            for (GCalEvent calEvent : events) {
                gcal.insertItem(calEvent);
                String tmp = (i++) + ") event: " + calEvent;
                System.out.println(tmp);
                updateStatusArea.setText(updateStatusArea.getText() + tmp + "\n");
                updateStatusArea.repaint();
                updateStatusArea.revalidate();

            }
            FileUtil.sharedInstance.writeToFile(GCal.GANNT_FILE, "</data>");
        } catch (Exception ex) {
            Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, "Cannot insert events", ex);
        }
    }//GEN-LAST:event_updateCalButtonActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                try {
                    new MainFrame().setVisible(true);
                } catch (Exception ex) {
                    Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cleanCalButton;
    private javax.swing.JTextArea cleanStatusArea;
    private javax.swing.JButton exitButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTextArea projectsUrlsArea;
    private javax.swing.JButton updateCalButton;
    private javax.swing.JTextArea updateStatusArea;
    // End of variables declaration//GEN-END:variables
}
